package com.example.demo.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.example.demo.service.OssService;
import com.example.demo.utlis.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl  implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        //获取阿里云存储相关常量
        String endPoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        try {
            //1、bucketName 2、路径和文件名3、输入流
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            //在文件中添加一个随机值 防止覆盖
            String uuid = UUID.randomUUID().toString().replaceAll("-","");

            //获取当前日期
            String dataPath = new DateTime().toString("yyyy/MM/dd");
            originalFilename=dataPath+"/"+uuid+originalFilename;
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, originalFilename, inputStream);
            //返回上传数据的路径
            String url = "https://"+bucketName+"."+endPoint+"/"+originalFilename;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
